# -*- coding:UTF-8 -*-
# file   : FileChooser.py
# time   : 2023/12/5 
# author : panghu
# Desc   : 文件选择器

from PySide6.QtWidgets import QWidget, QVBoxLayout, QPushButton, QLabel, QFileDialog, QMessageBox
from PySide6.QtCore import Qt
import os


def get_filename_and_extension(file_path):
    # 分离文件名和扩展名
    base_name = os.path.basename(file_path)
    file_name, extension = os.path.splitext(base_name)
    folder_path = file_path.replace(f"{file_name}{extension}", "")
    return file_name, extension, folder_path


class FileChooser(QWidget):
    def __init__(self, check_endswith=None, file_filter="All Files (*.*)", file_type="", file_selected_callback=None):
        super().__init__()
        self.button = None
        self.label = None
        self.layout = None
        self.check_endswith = check_endswith
        self.file_type = file_type
        self.file_filter = file_filter
        self.file_selected_callback = file_selected_callback
        self.initUI()
        self.setAcceptDrops(True)

    def initUI(self):
        self.layout = QVBoxLayout()

        self.label = QLabel(f"拖拽{self.file_type}文件到这里或点击按钮选择{self.file_type}文件")
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setStyleSheet("border: 2px dashed #aaa;")
        self.label.setAcceptDrops(True)

        self.button = QPushButton(f"选择{self.file_type}文件")
        self.button.clicked.connect(self.open_file_dialog)

        self.layout.addWidget(self.label)
        self.layout.addWidget(self.button)
        self.setLayout(self.layout)

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.acceptProposedAction()

    def dropEvent(self, event):
        file_path = event.mimeData().urls()[0].toLocalFile()
        if self.check_endswith is None or self.check_endswith(file_path.lower()):
            self.process_file(file_path)
        else:
            self.show_warning_dialog("不支持的文件类型", f"请拖拽一个 {self.file_type}文件。")

    def open_file_dialog(self):
        file_name, _ = QFileDialog.getOpenFileName(self, f"选择{self.file_type}文件", filter=self.file_filter)
        if file_name:
            self.process_file(file_name)

    def process_file(self, file_path):
        if self.file_selected_callback:
            self.file_selected_callback(file_path)
            file_name, file_ext, _ = get_filename_and_extension(file_path)
            self.label.setText(f"已选择{file_name}.{file_ext}")

    def show_warning_dialog(self, title, message):
        QMessageBox.warning(self, title, message)
